<template>
  <div class="space-y-2">
    <label v-if="label" :for="inputId" class="block text-sm font-medium text-foreground">
      {{ label }}
      <span v-if="required" class="text-red-500 ml-1">*</span>
    </label>

    <div class="relative">
      <!-- 货币符号 -->
      <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
        <span class="text-muted-foreground">{{ currency }}</span>
      </div>

      <input
        :id="inputId"
        :value="displayValue"
        type="text"
        :placeholder="placeholder"
        :disabled="disabled"
        :readonly="readonly"
        :required="required"
        :class="inputClasses"
        class="w-full pl-8 pr-3 py-2 border rounded-lg transition-colors focus:outline-none focus:ring-2 focus:ring-primary/20 focus:border-primary disabled:opacity-50 disabled:cursor-not-allowed text-right"
        @input="handleInput"
        @blur="handleBlur"
        @focus="handleFocus" />

      <!-- 错误图标 -->
      <div v-if="error" class="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none">
        <i class="i-mdi-alert-circle w-5 h-5 text-red-500" />
      </div>
    </div>

    <!-- 错误信息 -->
    <p v-if="error" class="text-sm text-red-500">{{ error }}</p>

    <!-- 帮助文本 -->
    <p v-if="help && !error" class="text-sm text-muted-foreground">{{ help }}</p>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';

interface Props {
  modelValue?: number;
  label?: string;
  placeholder?: string;
  disabled?: boolean;
  readonly?: boolean;
  required?: boolean;
  error?: string;
  help?: string;
  currency?: string;
  precision?: number;
  min?: number;
  max?: number;
}

interface Emits {
  (e: 'update:modelValue', value: number): void;
  (e: 'blur', event: FocusEvent): void;
  (e: 'focus', event: FocusEvent): void;
}

const props = withDefaults(defineProps<Props>(), {
  currency: '¥',
  precision: 2,
  min: 0
});

const emit = defineEmits<Emits>();

const inputId = ref(`money-input-${Math.random().toString(36).substr(2, 9)}`);

const displayValue = computed(() => {
  if (props.modelValue === undefined || props.modelValue === null) {
    return '';
  }
  return formatMoney(props.modelValue);
});

const inputClasses = computed(() => {
  const classes: string[] = [];

  // 基础样式
  classes.push('bg-background border-border text-foreground');

  // 错误状态
  if (props.error) {
    classes.push('border-red-500 focus:border-red-500 focus:ring-red-500/20');
  } else {
    classes.push('border-gray-300 dark:border-gray-600');
  }

  return classes.join(' ');
});

const formatMoney = (value: number): string => {
  return value.toLocaleString('zh-CN', {
    minimumFractionDigits: props.precision,
    maximumFractionDigits: props.precision
  });
};

const parseMoney = (value: string): number => {
  // 移除所有非数字和小数点的字符
  const cleaned = value.replace(/[^\d.-]/g, '');
  const parsed = parseFloat(cleaned);
  return isNaN(parsed) ? 0 : parsed;
};

const handleInput = (event: Event) => {
  const target = event.target as HTMLInputElement;
  const rawValue = target.value;
  const numericValue = parseMoney(rawValue);

  // 应用最小值和最大值限制
  let finalValue = numericValue;
  if (props.min !== undefined && finalValue < props.min) {
    finalValue = props.min;
  }
  if (props.max !== undefined && finalValue > props.max) {
    finalValue = props.max;
  }

  emit('update:modelValue', finalValue);
};

const handleBlur = (event: FocusEvent) => {
  emit('blur', event);
};

const handleFocus = (event: FocusEvent) => {
  const target = event.target as HTMLInputElement;
  // 聚焦时选中所有文本
  target.select();
  emit('focus', event);
};
</script>
